<template>
  <div class="ingredient_manager">
    <div class="ingredient_title">{{ id ? '编辑' : '新增'}}食材</div>
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="form.name"
          maxlength="50"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="图片" prop="image">
        <el-upload
          :accept="uploadImageAccept"
          :show-file-list="false"
          action="no"
          :before-upload="beforeAvatarUpload"
          :http-request="selfUploadWork"
          list-type="picture-card"
        >
          <el-icon v-if="!form.image"><Plus /></el-icon>
          <div v-else class="upload_contont">
            <img class="upload_img" :src="form.image" alt="" />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview()">
                <el-icon><zoom-in /></el-icon>
              </span>
              <span class="el-upload-list__item-delete" @click="handleRemove()">
                <el-icon><Delete /></el-icon>
              </span>
            </span>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="别名" prop="alias">
        <el-input
          v-model="form.alias"
          maxlength="50"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="main_text">
        <el-input
          v-model="form.main_text"
          type="textarea"
          :rows="15"
          maxlength="2000"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="营养成分" prop="nutrition_list">
        <addList v-model="form.nutrition_list" query-type="element"></addList>
      </el-form-item>
      <!-- <el-form-item label="常见食谱" prop="cook_list">
        <addList v-model="form.cook_list" query-type="element"></addList>
      </el-form-item> -->
    </el-form>
    <div class="operation">
      <div class="cancel_btn" @click="cancel">取消</div>
      <div class="submit_btn" @click="submit">提交</div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { Plus, Delete, ZoomIn } from '@element-plus/icons-vue'
import { addIngredient, updateIngredientById, getIngredientById, uploadImage } from '@/views/settings/backend/api'

import addList from '@/components/addList/index.vue'

const rules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  alias: [{ required: true, message: '请输入别名', trigger: 'blur' }],
  main_text: [{ required: true, message: '请输入描述', trigger: 'blur' }]
})

const resetFields = (formData) => {
  const data = formData || initForm
  form.value = { ...data }
  formRef.value.clearValidate()
}

let form = ref({})
const formRef = ref()
let id = ''

const uploadImageAccept =  '.jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP'

const initForm = {
  name: '',
  nutrition_list: '',
  cook_list: '',
  alias: '',
  main_text: '',
  image: '',
  icon: ''
}

onMounted(() => {
  const route = useRoute()
  id = route.query.id
  if (id) {
    getIngredientById(id).then(res => {
      form.value = res.result[0]
    })
  } else {
    form.value = { ...initForm }
  }
})

const beforeAvatarUpload = (val) => {
  const fileType = val.name.split('.').reverse()[0]
  const isJPG = uploadImageAccept.indexOf(fileType) !== -1
  const isLt2M = val.size / 1024 / 1024 < 20
  if (!isJPG) {
    this.$message.error('只能上传图片！')
  }
  if (!isLt2M) {
    this.$message.error('上传图片大小不能超过 20MB！')
  }
  return isJPG && isLt2M
}

const selfUploadWork = (val) => {
  const fd = new FormData()
  fd.append('file', val.file) // 传文件
  uploadImage(fd).then(res => {
    const result = res.result || {}
    form.value.image = result.file_path
    val.onSuccess(val)
  })
  .catch(() => {
    val.onError()
  })
}

const submit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (id) {
        const params = { ...form.value, id }
        updateIngredientById(params).then(() => {
          ElMessage({
            type: 'success',
            message: '修改成功'
          })
          cancel()
        })
      } else {
        addIngredient(form.value).then(() => {
          ElMessage({
            type: 'success',
            message: '添加成功'
          })
          resetFields()
        })
      }
    }
  })
}

const cancel = () => {
  history.back()
}
</script>

<style lang="scss" scoped>
.ingredient_manager {
  padding: 20px;
  width: calc(100% - 50px);

  .ingredient_title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 50px;
    border-left: 5px solid var(--el-color-primary);
    text-align: left;
    padding-left: 10px;
  }

  ::v-deep .el-form-item__label {
    display: block;
    font-weight: bold;
    text-align: left;
  }

  ::v-deep .el-form-item {
    display: block;
  }

  .upload_contont {
    width: 100%;
    height: 100%;
    border-radius: 6px;
    overflow: hidden;
    .upload_img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .operation {
    height: 50px;
    display: flex;
    justify-content: end;

    .cancel_btn {
      width: 100px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border: 1px solid var(--el-color-primary);
      border-radius: 5px;
      margin-right: 20px;
      cursor: pointer;
    }
    .submit_btn {
      width: 100px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: #fff;
      background-color: var(--el-color-primary);
      border-radius: 5px;
      cursor: pointer;
    }
  }
}
</style>